<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
	<title>Promise testDemo</title>
	<style type="text/css">
	* {
		padding: 0;
		margin: 0;
	}
	 
</style>
</head>
<body>
	<h1>aaaa</h1>
	<div id="box">
	    <h2>第九章 闭包与作用域</h2>
	    <button>收藏课程</button>
	  </div>
</body>
<script src="index.js"></script>
<script type="text/javascript"> 

// then 内部返回的 promise 更改外部的 promise 变量
// 为了让任务继承，执行完任务需要将 promise 状态修改为 fulfilled
class User {
  //加载用户
  ajax(user) {
    let url = `http://localhost/ajax/ajax3.php?&t=1&name=${user}`;
    return new Promise(resolve => {
      let xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.send();
      xhr.onload = function() {
        if (this.status == 200) {
          resolve(JSON.parse(this.response));
        } else {
          reject(this);
        }
      };
    });
  }
  //启动
  render(users) {
    users.reduce((promise, user) => {
      return promise
        .then(() => {
          return this.ajax(user);
        })
        .then(user => {
          return this.view(user);
        });
    }, Promise.resolve());
  }
  //宣染视图
  view(user) {
    return new Promise(resolve => {
      let h1 = document.createElement("h1");
      h1.innerHTML = user.name;
      document.body.appendChild(h1);
      resolve();
    });
  }
}
new User().render(["向军", "后盾人"]);

</script>
</html>